<!--数据回显-->
<!--1.提交数据报错后,将刚才提交的数据回显到表单中-->
<!--2.编辑数据的时候,取消编辑还原旧数据-->

<template>
	<section>

		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.findname" placeholder="部门名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :click="find">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd()">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>


    <!--列表-->
    <el-table :data="pageInfo" highlight-current-row  @selection-change="selsChange" style="width: 100%;">
<!--      选框-->
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" width="60">
      </el-table-column>

<!--      列表-->
<!--      :formatter="formatStatus"-->
      <el-table-column prop="name" label="部门名字" width="120" sortable>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="update_time" label="修改时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="经理名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门名" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="path" label="路径" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="180"  sortable>
        <template v-slot="scope">
          <span v-if="scope.row.state == 0" style="color: red;">禁用</span>
          <span v-if="scope.row.state == 1">启用</span>
        </template>
      </el-table-column>

      <el-table-column prop="intro" label="描述" width="120">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--批删和分页-->
<!--    page-size:每页显示条目个数-->
<!--    page-sizes:每页显示个数选项器-->
<!--    :disabled="this.sels.length === 0" 如果没有数据让删除按钮失效 -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemoveDept" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          layout="total, sizes,prev, pager, next,jumper"
          @current-change="handleCurrentChange"

          :page-size="query.pageSize"
          :page-sizes="[5,10,15,20,30]"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float:right;">
      </el-pagination>
    </el-col>

<!--****************************************************************************-->
<!--*****************************新增和编辑界面***********************************-->
<!--****************************************************************************-->
    <!--
    :visible.sync  控制dialog是否显示
     :rules  绑定表单校验规则
     prop:绑定校验规则的名称
   -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="su"><!-- ref给表单取别名 -->
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="0">禁用</el-radio>
            <el-radio class="radio" :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        ****************************************  -->
<!--      ****************编辑新增--下拉框****************  -->
<!--        ****************************************  -->
<!--数据类型不匹配会发生400错误-->
        <el-form-item label="经理名" prop="manager_id">
<!--          <el-input v-model="saveForm.manager_id" auto-complete="off"></el-input>-->
<!--          value-key:绑定为对象-->
              <el-select v-model="saveForm.manager" value-key="id" placeholder="选择">
                <el-option v-for=" manager in options"
                           :key="manager.id"
                           :label="manager.username"
                           :value="manager">
                </el-option>
              </el-select>
        </el-form-item>


        <el-form-item label="上级部门" prop="parent_id">
<!--          <el-input v-model="saveForm.parent_id" auto-complete="off"></el-input>-->
<!--          label用于显示的字段名,用于显示的字段值-->
<!--          @change="handleChange"-->

          <el-cascader
            v-model="saveForm.parent"
            :options="deptTree.data"
            :props="{
              checkStrictly:true,//是否可以选择树干结点作为选项
              label:'name',
              value:'id'
            }"
           clearable></el-cascader>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--****************************************************************************-->
    <!--****************************************************************************-->
    <!--****************************************************************************-->

	</section>
</template>

<script>
import {batchRemoveDep, removeDep, getDepList, addDep, findEmployees, DepTree} from "../../api/api";

  export default {
    name: "Department",
    // data为初始化页面值
    data() {
      return {
        deptForm:{

          //定义一个数组,存储复选框的值
          selectedOptions:[],
          id:null,
          name:null,
          intro:null,
          manager_id:null,
          parent_id:null,
          state:null,
          path:null,
          manager:null,
          parent:null
        },

        pageInfo: {
          // 总条数
          total: 0,
          rows: []
        },

        //初始化分页
        query: {
          //当前页码
          currentPage: 1,
          //每页显示条数
          pageSize: 10
        },
        /***************************************/

        //高级查询名字
        filters: {
          findname: ''
        },

        sels: [],//列表选中列，批删

        /***************************************************************/
        /******************初始化新增和编辑方法****************************/
        /***************************************************************/
        saveFormVisible: false,//新增界面是否显示
        saveLoading: false,
        options: [],
        title: "新增或修改店铺",
        // 表单校验规则
        //trigger:blur---失去焦点时触发验证
        saveFormRules: {
          name: [
            {required: true, message: '请输入部门名字', trigger: 'blur'}
          ]
        },
//新增界面数据
        saveForm: {
          name: '',
          intro: "",
          manager_id:"",
          state: null,
          parent:{
            id:null,
            name:"",
            length:null
          }
        },
        //下拉员工初始化数据
        employees: [],
        //父级部门树
        deptTree: [],

        // 显示新增
        //显示新增界面
        handleAdd() {
          this.saveFormVisible = true;
          this.saveForm = {
            id:null,
            name: '',
            intro: '',
            manager_id:null,
            parent:{
              id:null,
              name:"",
              length:null
            },
            state: null,
            path:null
          }
          this.loadDepTree()
        },

        //显示编辑界面,需要做数据回显
        //把row行中的数据拷贝到表单中去
        handleEdit(index, row) {
          Object.assign(this.saveForm, row)
          this.saveFormVisible = true;
          this.loadDepTree()
          //上级部门回显
          this.saveForm.parent = row.parent_id
        },

        /**************************************************************/
        /*****************************删除*********************************/
        /**************************************************************/
        //index:当前数据的行号
        //row:当前行数据
        handleDel(index, row) {
          this.$confirm('确认删除该记录吗?', '提示', {
            type: 'warning'
          }).then(() => {
            this.listLoading = true
            //NProgress.start();
            let para = {id: row.id}
            removeDep(para).then((res) => {
              this.listLoading = false
              //NProgress.done();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getDepartment()
            });
          }).catch(() => {

          });
        },


        // **************************************************//
        // *********************批删*************************//
        // **************************************************//


        //批量删除
        batchRemoveDept: function () {
          //箭头函数相当于function函数简写
          //去掉function,改成箭头=>
          //形参小括号写到箭头左边
          var ids = this.sels.map(item => item.id).toString()
          this.$confirm('确认删除选中记录吗？', '提示', {
            type: 'warning'
          }).then(() => {
            this.listLoading = true
            //NProgress.start();
            let para = {ids: ids}

            batchRemoveDep(para).then((res) => {

              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getDepartment()
            });
          }).catch(() => {

          });
        }
        // **************************************************
        // **************************************************
        // **************************************************
      }
    },


    methods: {
      //列表更改
      selsChange: function (sels) {
        this.sels = sels
      },


      //提交弹出框
      //$refs代表所有ref:取了别名的
      saveSubmit() {
        this.$refs.su.validate((valid) => {
          if (valid) {
            this.$confirm('确定提交么?', '提示', {}).then(() => {
              this.saveLoading = true

              //选择级联 null [1] [1,2]
              if(this.saveForm.parent){
                //取出最后一个值
                let index = this.saveForm.parent.length;

                this.saveForm.parent={
                  id:this.saveForm.parent[index-1]
                }
              }
              addDep(this.saveForm).then((res) => {
                if (res.data.success) {
                  this.$message({
                    message: '成功',
                    type: 'success'
                  })
                } else {
                  this.$message.error(res.data.message)
                }
                this.getDepartment()
                this.saveLoading = false
                this.saveFormVisible = false
              })
            })
          }
        })
      },


      find() {
        this.query.currentPage = 1
        this.getDepartment()
      },

      //js方法
      //账号状态转换
      // formatStatus: function (row, column) {
      // 	return row.state == 1 ? '正常' : row.state == 0 ? '停用' : '未知';
      // },

      //当前页码改变时触发
      handleCurrentChange(currentPage) {
        this.query.currentPage = currentPage
        this.getDepartment()
      },

      //页码大小改变时触发(success)
      handleSizeChange(pageSize) {
        this.query.pageSize = pageSize
        this.getDepartment()
      },

      //获取部门列表
      getDepartment() {
        this.listLoading = true
        //封装数据
        let query = {
          //this调用的是data里面的初始化数据
          currentPage: this.query.currentPage,
          pageSize: this.query.pageSize,
          findname: this.filters.findname
        }
        // this.$http.post("/dept",query)
        getDepList(query).then(res => {
//res.data.data返回数据需要嵌套一层
          res = res.data
          this.pageInfo = res.data

          // 总数
          this.pageInfo.total = res.count
          //关闭加载
          this.listLoading = false
        }).catch(result => {
          this.$message({message: '分页查询失败', type: 'error'});
        })
      },

      //下拉框
      loadEmployees() {
        findEmployees().then((res) => {
          this.options = res.data

        })
      },
      //部门树
      loadDepTree(){
        DepTree().then(res=>{
          this.deptTree = res.data
        })
      }


  },
    //页面加载时
    //要注意mounted位置
    mounted() {
      this.getDepartment()
      this.loadEmployees()
    }
}
</script>

<style scoped>

</style>